package com.ruoyi.project.applet.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.applet.domain.Order;
import com.ruoyi.project.applet.domain.Ratio;
import com.ruoyi.project.applet.domain.Shipping;
import com.ruoyi.project.applet.domain.Wallelog;
import com.ruoyi.project.applet.mapper.OrderMapper;
import com.ruoyi.project.applet.mapper.VipMapper;
import com.ruoyi.project.applet.service.IOrderService;
import com.ruoyi.project.system.domain.SysUserWx;
import com.ruoyi.project.system.mapper.SysUserWxMapper;
import com.ruoyi.project.system.service.ISysUserWxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-07
 */
@Service
public class OrderServiceImpl implements IOrderService {

    private Logger logger = LoggerFactory.getLogger("OrderServiceImpl");

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    ISysUserWxService userWxService;

    @Autowired
    private SysUserWxMapper sysUserWxMapper;

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private WallelogServiceImpl wallelogService;

    @Autowired
    private RatioServiceImpl ratioService;
    /**
     * 查询订单
     *
     * @param id 订单ID
     * @return 订单
     */
    @Override
    public Order selectOrderById(String id) {
        final Order order = orderMapper.selectOrderById(id);
        return order;
    }

    @Override
    public List<Order> selectOrderByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        final List<Order> orders = orderMapper.selectOrderByIds(ids);
        return orders;
    }

    @Override
    public Order selectOrderByOrderNumber(String orderNumber) {
        Order order = orderMapper.selectOrderByOrderNumber(orderNumber);
        return order;
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        List<Order> orders = orderMapper.selectOrderList(order);
        //设置下单人信息
        List<String> userIds = orders.stream().map(Order::getOpenId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(userIds)) {
            List<SysUserWx> userWxList = sysUserWxMapper.selectSysUserWxByOpenIds(userIds);
            for (Order order1 : orders) {
                for (SysUserWx userWx : userWxList) {
                    if (order1.getOpenId().equals(userWx.getOpenId())) {
                        order1.setBuyUser(userWx);
                        //当下下单人有推荐人时，填写推荐人信息
                    }
                }
            }
        }
        //获取分销比列
        List<Ratio> ratios = ratioService.selectRatioList(new Ratio());
        BigDecimal firstRatio = ratios.get(0).getFirstRatio();
        BigDecimal secondRatio = ratios.get(0).getSecondRatio();
        //设置一级推荐人信息
        List<String> firstParentIds = orders.stream().map(Order::getFirstParent).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(firstParentIds)) {
            List<SysUserWx> firstParentList = sysUserWxMapper.selectSysUserWxByOpenIds(firstParentIds);
            for (Order order1 : orders) {
                for (SysUserWx userWx : firstParentList) {
                    if (userWx.getOpenId().equals(order1.getFirstParent())) {
                        order1.setFirstReferee(userWx);
                        //一级分销金额
                        BigDecimal firstMoney = order1.getPayAmount().multiply(firstRatio);
                        order1.setFirstMoney(firstMoney);
                        //订单实际收入
                        order1.setIncome(order1.getPayAmount().subtract(firstMoney));
                    }
                }
           }
        }
        //设置二级推荐人信息
        List<String> secondParentIds = orders.stream().map(Order::getSecondParent).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(secondParentIds)) {
            List<SysUserWx> secondParentList = sysUserWxMapper.selectSysUserWxByOpenIds(secondParentIds);
            for (Order order1 : orders) {
                for (SysUserWx userWx : secondParentList) {
                    if (userWx.getOpenId().equals(order1.getSecondParent())) {
                        order1.setSecondReferee(userWx);
                        BigDecimal secondMoney = order1.getPayAmount().multiply(secondRatio);
                        order1.setSecondMoney(secondMoney);
                        order1.setIncome(order1.getIncome().subtract(secondMoney));
                    }
                }
            }
        }
        return orders;
    }

    @Override
    public List<Order> selectOrderByOpenIds(List<String> openIds) {
        if (openIds == null || openIds.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<Order> orders = orderMapper.selectOrderByOpenIds(openIds);
        return orders;
    }

    @Override
    public List<Order> selectFenxiaoOrderList(List<String> orderNumbers) {
        List<Order> orderList = orderMapper.selectOrderByNumbers(orderNumbers);
        //设置下单人和推荐人信息
        List<String> userIdList = orderList.stream().map(Order::getOpenId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(userIdList)) {
            List<SysUserWx> userWxList = sysUserWxMapper.selectSysUserWxByOpenIds(userIdList);
            for (Order order : orderList) {
                for (SysUserWx userWx : userWxList) {
                    if (order.getOpenId().equals(userWx.getOpenId())) {
                        order.setBuyUser(userWx);
                        //当下单人有推荐人时，填写推荐人信息
                        if (StringUtils.hasText(userWx.getParentId())) {
                            SysUserWx referee = sysUserWxMapper.selectSysUserWxByOpenId(userWx.getParentId());
                            order.setReferee(referee);
                            //设置订单佣金
                            Wallelog wallelog = new Wallelog();
                            wallelog.setUserId(referee.getOpenId());
                            wallelog.setOrderNumber(order.getNumber());
                            List<Wallelog> wallelogList = wallelogService.selectWallelogList(wallelog);
                            if (!CollectionUtils.isEmpty(wallelogList)) {
                                order.setCommission(wallelogList.get(0).getAmount());
                            }

                        }
                    }
                }
            }
        }
        return orderList;
    }

    @Override
    public List<Order> selectOrderByOpenId(String openId) {
        if (StringUtil.isEmpty(openId)) {
            return Collections.EMPTY_LIST;
        }
        List<Order> orders = orderMapper.selectOrderByOpenId(openId);

        return orders;
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        order.setCreateTime(DateUtils.getNowDate());
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(String[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderById(String id) {
        return orderMapper.deleteOrderById(id);
    }


}

